package com.hmy.security.util;

import com.hmy.security.security.bean.JwtUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
public class TokenUtil {

    private static String tokenSecret = "hello world";

    /**
     * 生成token
     * 使用到jjwt
     * @see <a href="https://cloud.tencent.com/developer/article/1784276">jjwt使用示例</a>
     * @return token
     */
    public static String genToken(String subject){
        return Jwts.builder()
                .setSubject(subject)
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
                .signWith(SignatureAlgorithm.HS256, tokenSecret)
                .compact();
    }

    /**
     * 获取token
     * @param request request
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        String token;
        if (StringUtils.isNotBlank(token = request.getParameter("token"))) {
            return token;
        }
        if (StringUtils.isNotBlank(token = request.getHeader("token"))) {
            return token;
        }
        return null;
    }

    /**
     * 判断token是否过期
     * @param token token
     * @return {@link Boolean}
     */
    public static boolean validateToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(tokenSecret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("getClaimsFromToken exception", e);
            claims = null;
        }
        if (claims == null) {
            return false;
        }
        return claims.getExpiration().after(new Date());

    }
}
